package ru.aslanov.schedule.utils;

import javax.xml.bind.JAXBContext;
import javax.xml.datatype.DatatypeConstants;
import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathFactory;
import java.util.Date;
import java.util.GregorianCalendar;

/**
 * Created by IntelliJ IDEA.
 * Created: Feb 2, 2010 11:05:20 AM
 *
 * @author Sergey Aslanov
 */
public class XMLUtil {
    public static final JAXBContext JAXB_CONTEXT;
    public static final DatatypeFactory DATATYPE_FACTORY;
    public static final DocumentBuilderFactory DOCUMENT_BUILDER_FACTORY;
    public static final XPathFactory X_PATH_FACTORY = XPathFactory.newInstance();

    static {
        try {
            JAXB_CONTEXT = JAXBContext.newInstance("ru.aslanov.schedule.model");

            DATATYPE_FACTORY = DatatypeFactory.newInstance();

            DOCUMENT_BUILDER_FACTORY = DocumentBuilderFactory.newInstance();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static XMLGregorianCalendar date2XmlDate(Date date, QName type) {
        if (date == null) return null;
        GregorianCalendar gregorianCalendar = new GregorianCalendar();
        gregorianCalendar.setTime(date);
        final XMLGregorianCalendar xmlGregorianCalendar = DATATYPE_FACTORY.newXMLGregorianCalendar(gregorianCalendar);
        if (type == DatatypeConstants.DATETIME) {
            // do nothing
        } else if (type == DatatypeConstants.DATE) {
            xmlGregorianCalendar.setHour(DatatypeConstants.FIELD_UNDEFINED);
            xmlGregorianCalendar.setMinute(DatatypeConstants.FIELD_UNDEFINED);
            xmlGregorianCalendar.setSecond(DatatypeConstants.FIELD_UNDEFINED);
            xmlGregorianCalendar.setTimezone(DatatypeConstants.FIELD_UNDEFINED);
        } else {
            throw new RuntimeException("Unsupported type: " + type);
        }
        return xmlGregorianCalendar;
    }


}
